<?php
/**
 * SiteController class file.
 *
 * @package   controllers
 * @since     1.0
 * @filesource
 */

/**
 * Site controller is the default controller that displays main index page, login and logout.
 * Controller class is also responsible for rendering page.
 */
class SiteController extends Controller
{
	/**
	 * Return a list of filters that will be used to control access.
	 * @return array action filters
	 */
	public function filters()
	{
		return array(
			'accessControl', // perform access control for CRUD operations
		);
	}

	/**
	 * Specifies the access control rules.
	 * This method is used by the 'accessControl' filter which is declared in $this->filters().
	 * @return array access control rules
	 */
	public function accessRules()
	{
		return array(
			array('allow', // allow authenticated user to view index and logout
				'actions'=>array('index','logout'),
				'users'=>array('@'),
			),
			array('allow', // allow all users to login and see error.
				'actions'=>array('error','login'),
				'users'=>array('*'),
			),
			array('deny',  // deny all other users
				'users'=>array('*'),
			),
		);
	}

	/**
	 * This is the default 'index' action that is invoked
	 * when an action is not explicitly requested by users.
	 * On the index page the welcome message and the statistics for
	 * organization is displayed. The user can view other organizations.
	 * @param int $organizationId the organization to view. if not specified the first viewable
	 * organization will be chosen.
	 * @throws CHttpException if the user is not able to view the specified organization.
	 */
	public function actionIndex($organizationId=false)
	{
		if(Yii::app()->user->isGuest){
			// redirect to login if user has not logged in
			$this->redirect(array('login'));
		}
		
		$params=array();// an array of variables used to render index page.
		
		// get an array of organizations that are viewable for current user.
		$viewableOrganizations=User::getCurrentUser()->viewableOrganizations;
		// check if the user has access to any organizations
		if(!empty($viewableOrganizations)){
			$params['viewableOrganizations']=$viewableOrganizations;
			if(!$organizationId){
				// if not specified organization, default select the first one.
				$params['organization']=$viewableOrganizations[0];
				$organizationId=$params['organization']->id;
			}else{
				// if specified organization, check if current user has view access to the given organization.
				if(Yii::app()->user->checkAccess('signalView',array(
				'organizationId'=>$organizationId
				))){
					$params['organization']=Organization::model()->findByPk($organizationId);
					if(!$params['organization']){
						throw new CHttpException(404, "Organization Not found.");
					}
				}else{
					throw new CHttpException(401, "Access denied to view organization.");
				}
			}
			// calculate the numbers of patient signals for each combination of disorder and gender in the specified organization.
			$dbCommand = Yii::app()->db->createCommand("SELECT d.name as disorder,gender,COUNT(*) as count FROM {{patient_signal}} as p,{{disorder}} as d where p.disorderId=d.id
			and p.organizationId=$organizationId
			GROUP BY `disorderId`,`gender`");
			$data = $dbCommand->queryAll();
			// pre-calculate data. As there may be 0 results for certain gender and disorder so the data should be pre-processed
			// reorganise the $data into format $disorder[disorderName][gender]
			$disorders=array();
			foreach($data as $row){
				$disorder=$row['disorder'];
				if(!isset($disorders[$disorder])){
					$disorders[$disorder]=array('female'=>0,'male'=>0);					
				}
				$disorders[$disorder][$row['gender']==DataUtil::VALUE_FEMALE?'female':'male']=$row['count'];
			}
			// output the result in expected format to render the bar chart.
			$organizationSummary=array(
				'disorders'=>array(),
				'female'=>array(),
				'male'=>array()
			);
			foreach ($disorders as $disorder=>$count){
				$organizationSummary['disorders'][]=$disorder;
				$organizationSummary['female'][]=$count['female'];
				$organizationSummary['male'][]=$count['male'];
			}
			$params['organizationSummary']=$organizationSummary;
		}

		$this->render('index',$params);
	}

	/**
	 * This is the action to handle external exceptions.
	 * This action will render an error page to display appropriate error information or for ajax request, return
	 * an error message.
	 */
	public function actionError()
	{
	    if($error=Yii::app()->errorHandler->error)
	    {
	    	if(Yii::app()->request->isAjaxRequest)
	    		echo $error['message'];
	    	else
	        	$this->render('error', $error);
	    }
	}

	/**
	 * Displays the login page or authenticates a pair of username and password.
	 */
	public function actionLogin()
	{
		$model=new LoginForm;

		// if it is ajax validation request, just carry out all validations and exit application.
		if(isset($_POST['ajax']) && $_POST['ajax']==='login-form')
		{
			//using CActiveForm::validate() to do Ajax validation and echo return values in JSON.
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}

		// if it is a login request with given username, password and remember me, 
		// the validation and model login method will be carried out.
		if(isset($_POST['LoginForm']))
		{
			//Assign all request value to model's parameters.
			$model->attributes=$_POST['LoginForm'];
			// validate user input and redirect to the previous page if input valid and login successful.
			if($model->validate() && $model->login())
				$this->redirect(Yii::app()->user->returnUrl);
		}elseif(isset($_POST["username"])&&isset($_POST["passwd"])){
			//The login is from home page of Nerual's main site
			$model->attributes=array(
				'username'=>$_POST["username"],
				'password'=>$_POST["passwd"],
				'rememberMe'=>0
			);
			// validate user input and redirect to the previous page if input valid and login successful.
			if($model->validate() && $model->login())
				$this->redirect(Yii::app()->user->returnUrl);
		}
		
		// display the login form
		$this->render('login',array('model'=>$model));
	}

	/**
	 * Logs out the current user and redirect to specified page or home page, depending on admin configuration.
	 */
	public function actionLogout()
	{
		Yii::app()->user->logout();
		$redirectUrl=GlobalConfiguration::getByKey('LOGOUT_REDIRECT');
		$this->redirect(empty($redirectUrl)?Yii::app()->homeUrl:$redirectUrl);
	}
}